package com.yjc.drygoods.search.controller;

import com.alibaba.fastjson.TypeReference;
import com.yjc.common.constant.AuthServerConstant;
import com.yjc.common.to.PurchaseDetailTo;
import com.yjc.common.to.SkuInfoTo;
import com.yjc.common.utils.R;
import com.yjc.common.vo.MemberRespVo;
import com.yjc.drygoods.search.feign.ProductFeignService;
import com.yjc.drygoods.search.servcie.MallSearchService;
import com.yjc.drygoods.search.vo.SearchParam;
import com.yjc.drygoods.search.vo.SearchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author yjc
 * @create 2022-09-12 16:37
 */
@Controller
public class SearchController {

    @Autowired
    MallSearchService mallSearchService;

    @Autowired
    ProductFeignService productFeignService;

    /**
     * 分析es中指定干货的上一年(或者上两年)的当前月份的平均每批进货数，得到需要采购的数量
     *
     * @return
     */
    @ResponseBody
    @GetMapping("/search/oldyear/month/avg/purchase/spunum")
    public R searchPurchaseSpuNum(@RequestParam("spuId") Long spuId) {
        Double spuNum = mallSearchService.searchPurchaseSpuNum(spuId);
        return R.ok().setData(spuNum);
    }


    @GetMapping("/list.html")
    public String listPage(SearchParam searchParam, Model model, HttpServletRequest request) {
        MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
        String queryString = request.getQueryString();
        searchParam.setQueryString(queryString);
        //查询的干货信息
        SearchResult searchResult = mallSearchService.search(searchParam);
        model.addAttribute("searchResult", searchResult);
        //查询当前用户可能喜欢的商品信息
        R r = null;
        if (attribute == null) {
            r = productFeignService.getUserLikeSkuInfo(null);
        } else {
            r = productFeignService.getUserLikeSkuInfo(attribute.getUsername());
        }
        if (r.getCode() == 0) {
            List<SkuInfoTo> data = r.getData(new TypeReference<List<SkuInfoTo>>() {
            });
            model.addAttribute("likeSkuInfos", data);
        }
        return "list";
    }
}
